package com.example.oop.Threads;

import com.example.oop.POJO.Player;
import com.example.oop.Repository.PlayerRepository;
import com.example.oop.Repository.RepositoryManager;
import com.example.oop.Service.PlayService;

import java.util.List;
import java.util.Optional;

//该线程用于进行准备好玩家的搜索，当准备状态的玩家大于等于两名，则为两位玩家同时切换为对局状态
public class FindReadyPlayer extends Thread {
    public static FindReadyPlayer findReadyPlayer = new FindReadyPlayer();
    private static PlayerRepository playerRepository;
    private PlayService playService;

    boolean quitFlag = false;

    private FindReadyPlayer() {
        playerRepository = RepositoryManager.playerRepository;
    }

    //用来终止当前进程
    public void doStop() {
        quitFlag = true;
        this.interrupt(); // 让  sleep() 立即中止
        try {
            this.join(); // 等待本线程结束后再退出
        } catch (Exception e) {
        }
    }

    public void run() {
        while (!quitFlag) {
            try {
                sleep(200);  //每0.2s执行一次
                findReadyPlayer();
            } catch (Exception e) {
            }
        }
    }

    private synchronized void findReadyPlayer() {
        synchronized (RepositoryManager.playerRepository) {  //互斥使用该repository
            List<Optional<Player>> players = null;
            players = playerRepository.findByStatus(1);

            if (players == null || players.size() < 2) return;  //没有足够的准备用户
            else {
                playService = new PlayService();
                int size = players.size();
//                System.out.println(size);
                for (int i = 0; i < size; i += 2) {
                    if (i + 1 < size) {
                        playService.beginPlay(players.get(i).get(), players.get(i + 1).get());  //选取两个人开始游戏
                    }
                }
            }
        }
    }
}
